06. Scanner
Scanner
ND079 C1 L4 A06 Scanner
The Scanner
class can read and parse simple text. Here are some key points to keep in mind:
- It parses primitive types and String types into tokens.
- By default it uses whitespaces to delimitate each word. However, it can also use regular expressions.
- The Scanner class can read from several different types of sources, like strings, files and
System.in
(to get input from the command line).
Scanner Syntax
Example 1
We can use the Scanner
class to get input from the command line. To do so, we instantiate a scanner object, passing in System.in
:
Scanner scanner = new Scanner(System.in);
Example 2
In this example we are using the nextLine
method to return the full line of the input:
Scanner scanner = new Scanner("This is a line");
System.out.println(scanner.nextLine());
Output:
This is a line
Example 3
In this next example, we are using the next
method to read the first token. The next
method finds and returns the next complete token.
Scanner scanner = new Scanner("This is a line");
System.out.println(scanner.next());
Output:
This
Example 4
In the final example, we are using the hasNext()
method in a while
loop to determine if it is safe to call the next method. We only want to call the next method when we know there is a token available.
Note: By default the Scanner tokenizes input by whitespaces. Let's say we have a string with the following text
"One Two Three"
. The text will be tokenized into three separate tokens,"One"
,"Two"
and"Three"
.
Scanner scanner = new Scanner("This is a line");
while(scanner.hasNext()) {
System.out.println(scanner.next());
}
**Output: **
This
is
a
line
SOLUTION:
- The Scanner class can be used to read input from the console.
- The Scanner class can also use RegEx to parse console input.
QUIZ QUESTION::
Match the code with the correct output for the String "1 number";
ANSWER CHOICES:
Code |
Output |
---|---|
|
|
|
|
|
|
|
SOLUTION:
Code |
Output |
---|---|
|
|
|
|
|
|
|
|
|
|
|
Additional Resources
- Java also has two other classes,
BufferedReader
andConsole
, that can be used to read user input from the command line. If you'd like to learn more, you can check out this article on three ways to read user input from the console.